package com.yc.mybatis.mybatisplusgenerator.platform.generator;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class CodeGenerator {

    private static String path;

    @Value("${base.projectPath}")
    public void setPath(String path) {
        CodeGenerator.path = path;
    }

    private static String packagePath;

    @Value("${base.package}")
    public void setPackagePath(String packagePath) {
        CodeGenerator.packagePath = packagePath;
    }

    private static String moduleName;

    @Value("${base.moduleName}")
    public void setModuleName(String moduleName) {
        CodeGenerator.moduleName = moduleName;
    }

    private static String table;

    @Value("${base.table}")
    public void setTable(String table) {
        CodeGenerator.table = table;
    }

    private static String noTable;

    @Value("${base.noTable}")
    public void setNoTable(String noTable) {
        CodeGenerator.noTable = noTable;
    }

    private static String author;

    @Value("${base.author}")
    public void setAuthor(String author) {
        CodeGenerator.author = author;
    }

    private static String logicDeleteField;

    @Value("${base.logicDeleteField}")
    public void setLogicDeleteField(String logicDeleteField) {
        CodeGenerator.logicDeleteField = logicDeleteField;
    }

    private static String superController;

    @Value("${base.superController}")
    public void setSuperController(String superController) {
        CodeGenerator.superController = superController;
    }

    private static String dbType;

    @Value("${datasource.dbType}")
    public void setDbType(String dbType) {
        CodeGenerator.dbType = dbType;
    }

    private static String idType;

    @Value("${base.idType}")
    public void setIdType(String idType) {
        CodeGenerator.idType = idType;
    }

    private static String tablePrefix;

    @Value("${base.tablePrefix}")
    public void setTablePrefix(String tablePrefix) {
        CodeGenerator.tablePrefix = tablePrefix;
    }

    private static String listShowField;

    @Value("${base.listShowField}")
    public void setListShowField(String listShowField) {
        CodeGenerator.listShowField = listShowField;
    }

    private static String formShowField;

    @Value("${base.formShowField}")
    public void setFormShowField(String formShowField) {
        CodeGenerator.formShowField = formShowField;
    }

    private static String driverClassName;

    @Value("${datasource.driverClassName}")
    public void setDriverClassName(String driverClassName) {
        CodeGenerator.driverClassName = driverClassName;
    }

    private static String url;

    @Value("${datasource.url}")
    public void setUrl(String url) {
        CodeGenerator.url = url;
    }

    private static String username;

    @Value("${datasource.username}")
    public void setUsername(String username) {
        CodeGenerator.username = username;
    }

    private static String password;

    @Value("${datasource.password}")
    public void setPassword(String password) {
        CodeGenerator.password = password;
    }

    private static String select;

    @Value("${base.select}")
    public void setSelect(String select) {
        CodeGenerator.select = select;
    }

    private static String checkbox;

    @Value("${base.checkbox}")
    public void setCheckbox(String checkbox) {
        CodeGenerator.checkbox = checkbox;
    }

    private static String radio;

    @Value("${base.radio}")
    public void setRadio(String radio) {
        CodeGenerator.radio = radio;
    }

    public static void Generator() {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        //文件输出路径
        String projectPath = path;
        String outPutDir = path + "/src/main/java";
        gc.setOutputDir(outPutDir);
        gc.setAuthor(author);
        gc.setOpen(false);
        //开启xml文件输出基本内容
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        //自定类名称
//        gc.setEntityName("%sEntity");
        //是否覆盖已有文件
        gc.setFileOverride(true);
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);
        //指定生成的主键的ID类型
        if (StringUtils.isNotEmpty(idType) && "UUID".equals(idType.toUpperCase())) {
            gc.setIdType(IdType.UUID);
        } else {
            gc.setIdType(IdType.AUTO);
        }

        // 数据源配置,自动识别数据库类型
        DataSourceConfig dsc = new DataSourceConfig();
        //自定义数据库的数据类型转换器
        // dsc.setTypeConvert(new SqlServerTypeConvertTwo());
        dsc.setTypeConvert(new MySqlTypeConvert());
        //自定义数据库查询语句
        //dsc.setDbQuery(new SqlServerDbQuery());
        dsc.setDbQuery(new MySqlQuery());
        //数据库Schema
//         dsc.setSchemaName("public");
        dsc.setUrl(url);
        dsc.setDriverName(driverClassName);
        dsc.setUsername(username);
        dsc.setPassword(password);


        if (dbType.toLowerCase().equals("sqlserver")) {
            dsc.setDbType(DbType.SQL_SERVER);
        } else if (dbType.toLowerCase().equals("sqlserver2005")) {
            dsc.setDbType(DbType.SQL_SERVER2005);
        } else if (dbType.toLowerCase().equals("mysql")) {
            dsc.setDbType(DbType.MYSQL);
        } else if (dbType.toLowerCase().equals("oracle")) {
            dsc.setDbType(DbType.ORACLE);
        } else if (dbType.toLowerCase().equals("db2")) {
            dsc.setDbType(DbType.DB2);
        } else if (dbType.toLowerCase().equals("h2")) {
            dsc.setDbType(DbType.H2);
        } else if (dbType.toLowerCase().equals("other")) {
            dsc.setDbType(DbType.OTHER);
        }
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(packagePath);
        pc.setModuleName(moduleName.equals("") ? null : moduleName);
        //自定单个类的输出包路径
//        pc.setController("controller."+packageName);
//        pc.setEntity("entity."+packageName);
//        pc.setMapper("dao."+packageName);
//        pc.setService("service."+packageName);
//        pc.setServiceImpl("service.impl."+packageName);
        mpg.setPackageInfo(pc);


//======================================自定义独立模板与自定值========================================================
        // 自定义标签
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                //自定义标签
                Map<String, Object> map = new HashMap<>();
                //处理下拉框
                JSONArray jsonArray = new JSONArray();
                if (StringUtils.isNotEmpty(select)) {
                    String[] strs = select.split(",");
                    jsonArray.addAll(toJson("select", strs));
                }

                //处理复选框
                if (StringUtils.isNotEmpty(checkbox)) {
                    String[] strc = checkbox.split(",");
                    jsonArray.addAll(toJson("checkbox", strc));
                }
                //处理单选框
                if (StringUtils.isNotEmpty(radio)) {
                    String[] strr = radio.split(",");
                    jsonArray.addAll(toJson("radio", strr));
                }
                map.put("customize", jsonArray);
                //主键策略
                if (StringUtils.isNotEmpty(idType) && "UUID".equals(idType.toUpperCase())) {
                    map.put("idType", "UUID");
                    map.put("idValue", UUID.randomUUID().toString().replaceAll("-", "").replaceFirst(".", ""));
                } else {
                    map.put("idType", "AUTO");
                }
                //显示字段控制
                if (StringUtils.isNotEmpty(listShowField)) {
                    String[] listField = listShowField.split(";");
                    Map<String, Object> fields = new HashMap<>(16);
                    for (String str : listField) {
                        String[] field = str.split(">");
                        fields.put(field[0].trim(), field[1].trim());
                    }
                    map.put("listField", fields);
                }
                if (StringUtils.isNotEmpty(formShowField)) {
                    String[] formField = formShowField.split(";");
                    Map<String, Object> fields = new HashMap<>(16);
                    for (String str : formField) {
                        String[] field = str.split(">");
                        fields.put(field[0].trim(), field[1].trim());
                    }
                    map.put("formField", fields);
                }
                this.setMap(map);
            }
        };

        // 如果模板引擎是 freemarker
//        String templatePath = "/templates/mapper.xml.ftl";
        // 添加自定义模板引擎 如果模板引擎是 velocity 可以定义多个
        String dto_template_path = "/templates/dto.java.vm";
        String mapper_template_path = "/templates/mapper.xml.vm";
        String dao_template_path = "/templates/mapper.java.vm";
        String entity_template_path = "/templates/entity.java.vm";
        String vo_template_path = "/templates/vo.java.vm";
//        String pageVo_template_path = "/templates/pageVo.java.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(dao_template_path) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return outPutDir + "/" + pc.getParent().replaceAll("\\.", "/") + "/mapper/" + tableInfo.getEntityName() + "Mapper.java";
            }
        });
        focList.add(new FileOutConfig(mapper_template_path) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return projectPath + "/src/main/resources/mapper/" + (pc.getModuleName() == null ? "" : pc.getModuleName() + "/") + tableInfo.getEntityName() + "Mapper.xml";
            }
        });
        //定义DTO
        focList.add(new FileOutConfig(dto_template_path) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return outPutDir + "/" + pc.getParent().replaceAll("\\.", "/") + "/dto/" + tableInfo.getEntityName() + "Dto.java";
            }
        });
        focList.add(new FileOutConfig(vo_template_path) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return outPutDir + "/" + pc.getParent().replaceAll("\\.", "/") + "/vo/" + tableInfo.getEntityName() + "Vo.java";
            }
        });
//        focList.add(new FileOutConfig(pageVo_template_path) {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输出文件名
//                return outPutDir + "/" + pc.getParent().replaceAll("\\.", "/") + "/vo/" + tableInfo.getEntityName() + "PageVo.java";
//            }
//        });
        focList.add(new FileOutConfig(entity_template_path) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名
                return outPutDir + "/" + pc.getParent().replaceAll("\\.", "/") + "/entity/" + tableInfo.getEntityName() + ".java";
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
//======================================END========================================================


        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
//         templateConfig.setEntity("templates/entity2.java");
//         templateConfig.setService();
        String controller_templates = "templates/controller.java";
        String service_templates = "templates/service.java";
        String serviceImpl_templates = "templates/serviceImpl.java";
        templateConfig.setController(controller_templates);
        templateConfig.setService(service_templates);
        templateConfig.setServiceImpl(serviceImpl_templates);
        //设置为null将不生成
        templateConfig.setEntity(null);

        templateConfig.setXml(null);
        templateConfig.setMapper(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSkipView(Boolean.TRUE);
        //表前缀
        if (StringUtils.isNotEmpty(tablePrefix)) {
            String[] prefixs = tablePrefix.split(",");
            strategy.setTablePrefix(prefixs);
        }

        //项目根据实际情况自己定义
//        strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.plugins.pagination.Page");
        strategy.setEntityLombokModel(Boolean.TRUE);
        //逻辑删除字段
        if (StringUtils.isNotEmpty(logicDeleteField)) {
            strategy.setLogicDeleteFieldName(logicDeleteField);
        }
        strategy.setRestControllerStyle(Boolean.TRUE);
        if (StringUtils.isNotEmpty(superController)) {
            strategy.setSuperControllerClass(superController);
        }
        if (StringUtils.isNotEmpty(table)) {
            String[] tables = table.split(",");
            strategy.setInclude(tables);
        } else
            //需要排除的表
            if (StringUtils.isNotEmpty(noTable)) {
                String[] noTables = noTable.split(",");
                strategy.setExclude(noTables);
            }
//        strategy.setSuperEntityColumns("id");
        strategy.setControllerMappingHyphenStyle(Boolean.FALSE);
//        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        //可以切换模板
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        //执行
        mpg.execute();
    }

    /**
     * 构建JSON
     *
     * @param strs
     * @return
     */
    private static JSONArray toJson(String style, String... strs) {
        String json = "[";
        for (String str : strs) {
            String[] k_v = str.split(":");
            json += "{\"field\":\"" + k_v[0] + "\",";
            if (k_v.length > 4) {
                json += "\"url\":\"" + k_v[1] + "\",\"type\":\"" + k_v[2] + "\",\"key\":\"" + k_v[3].replace("{", "") + "\",\"val\":\"" + k_v[4].replace("}", "") + "\"";
            } else {
                json += "\"url\":\"" + k_v[1] + "\",\"key\":\"" + k_v[2].replace("{", "") + "\",\"val\":\"" + k_v[3].replace("}", "") + "\"";
            }
            json += ",\"style\":\"" + style + "\"},";
        }
        json = json.substring(0, json.lastIndexOf(",")) + "]";
        return JSONArray.parseArray(json);
    }

}
